package com.layui.ad.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.layui.ad.annotation.DataSource;
import com.layui.ad.entity.Role;
import com.layui.ad.entity.RoleMenu;
import com.layui.ad.enums.DataSourceEnum;
import com.layui.ad.mapper.RoleMapper;
import com.layui.ad.mapper.RoleMenuMapper;
import com.layui.ad.query.RoleQuery;
import com.layui.ad.service.RoleService;
import com.layui.ad.utils.JsonResult;
import com.layui.ad.utils.StringUtils;
import com.layui.ad.vo.RoleListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>  implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult getList(RoleQuery query){
        // 查询条件
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        // 角色名称
        if (!StringUtils.isEmpty(query.getName())) {
            queryWrapper.like("name", query.getName());
        }
        // 状态：1正常 2禁用
        if (query.getStatus() != null) {
            queryWrapper.eq("status", query.getStatus());
        }
        queryWrapper.orderByDesc("id");


        // 查询数据
        IPage<Role> page = new Page<>(query.getPage(), query.getLimit());
        IPage<Role> data = roleMapper.selectPage(page, queryWrapper);
        List<Role> roleList = data.getRecords();
        List<RoleListVo> roleListVoList = new ArrayList<>();
        if (!roleList.isEmpty()) {
            roleList.forEach(item -> {
                RoleListVo roleListVo = new RoleListVo();
                // 拷贝属性
                BeanUtils.copyProperties(item, roleListVo);
                // 状态描述
//                if (roleListVo.getStatus() != null && roleListVo.getStatus() > 0) {
//                    roleListVo.setStatusName(RoleConstant.ROLE_STATUS_LIST.get(roleListVo.getStatus()));
//                }
//                // 添加人名称
//                if (roleListVo.getCreateUser() > 0) {
//                    roleListVo.setCreateUserName(AdminUtils.getName((roleListVo.getCreateUser())));
//                }
//                // 更新人名称
//                if (roleListVo.getUpdateUser() > 0) {
//                    roleListVo.setUpdateUserName(AdminUtils.getName((roleListVo.getUpdateUser())));
//                }
                roleListVoList.add(roleListVo);
            });
        }
        return JsonResult.ok("操作成功", roleListVoList, data.getTotal());
    }

    /**
     * 根据ID获取角色信息
     */
    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public Map<String,Object> info(Integer id){
        Object role = roleMapper.selectById(id);
        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(role), new TypeReference<Map<String, Object>>() {
        });
        return map;
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult edit( Role role){
        if(null == role){
            return JsonResult.fail("实体对象不存在");
        }
        Boolean num;
        if(role.getId() != null && role.getId()>0){
             num = this.updateById(role);
        }else {
             num = this.save(role);
        }
        if(num) {
            return JsonResult.ok();
        }else{
            return JsonResult.fail();
        }
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public JsonResult delete(Integer id){
        if(id ==null || id==0){
            return JsonResult.fail("缺少参数");
        }
        Role role = this.getById(id);
        if(role == null){
            return JsonResult.fail("数据不存在");
        }

        boolean flag = this.removeById(id);
        QueryWrapper<RoleMenu>  queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",id);
        Integer num = roleMenuMapper.delete(queryWrapper);
        if(flag && num>0) {
            return JsonResult.ok();
        }else{
            return JsonResult.fail();
        }
    }

    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    @Transactional(rollbackFor = {RuntimeException.class,Error.class})
    public JsonResult batchDelete(String ids){
        String[] idsList = ids.split(",");
        List<String> integerList = Arrays.asList(idsList);
//        for(String s:idsList){
//            roleMapper.deleteById(Integer.valueOf(s));
//            QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("role_id",Integer.valueOf(s));
//            roleMenuMapper.delete(queryWrapper);
//        }
        roleMapper.deleteBatchIds(integerList);
        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("role_id",integerList);
        roleMenuMapper.delete(queryWrapper);
        return JsonResult.ok();
    }


    @Override
    @DataSource(DataSourceEnum.SYSSOURCE)
    public JsonResult setStatus(Role role){
        Integer num = roleMapper.updateById(role);
        if(num>0){
            return JsonResult.ok();
        }else{
            return JsonResult.fail();
        }
    }
}
